import requests
from PIL import Image
import io
import os
import uuid
from datetime import datetime
from config.config import HF_API_KEY, HF_API_URL, UPLOAD_FOLDER
from models.history import History

class EmojiService:
    @staticmethod
    def generate_emoji(text, style='cartoon', is_dynamic=False, user_id=None, quality=75):
        """生成表情包"""
        if not text:
            return {'status': 'error', 'message': '文本内容不能为空'}, 400

        # 检查API密钥
        if not HF_API_KEY:
            return {'status': 'error', 'message': 'API密钥未配置，无法生成图片'}, 500

        # 调用Stable Diffusion API
        headers = {
            "Authorization": f"Bearer {HF_API_KEY}"
        }
        
        # 根据风格调整提示词
        style_prompts = {
            'cartoon': 'cartoon style, cute, simple, ',
            'realistic': 'realistic style, detailed, ',
            'funny': 'funny, exaggerated, comic style, ',
            'cute': 'kawaii, adorable, chibi style, '
        }
        prompt = f"{style_prompts.get(style, '')}emoji of {text}"
        
        try:
            response = requests.post(HF_API_URL, headers=headers, json={
                "inputs": prompt,
            }, timeout=30)
            
            if response.status_code != 200:
                return {
                    'status': 'error',
                    'message': f'图片生成失败，状态码: {response.status_code}'
                }, 500
        except requests.exceptions.RequestException as e:
            return {
                'status': 'error',
                'message': f'API请求失败: {str(e)}'
            }, 500

        # 保存图片
        try:
            image = Image.open(io.BytesIO(response.content))
            file_name = f"{uuid.uuid4()}.png"
            file_path = os.path.join(UPLOAD_FOLDER, file_name)
            image.save(file_path, quality=quality)
        except Exception as e:
            return {
                'status': 'error',
                'message': f'图片处理失败: {str(e)}'
            }, 500

        # 如果是动态表情包，进行额外处理
        if is_dynamic:
            try:
                from utils.emoji_animator import EmojiAnimator
                gif_file_name = f"{uuid.uuid4()}.gif"
                gif_file_path = os.path.join(UPLOAD_FOLDER, gif_file_name)
                
                # 创建动画效果
                animator = EmojiAnimator(file_path, gif_file_path)
                effect_success = animator.create_bounce_effect()
                
                if effect_success:
                    # 使用GIF文件路径
                    file_name = gif_file_name
                    file_path = gif_file_path
                else:
                    print("动态效果创建失败，使用原始图片")
            except ImportError:
                print("未找到emoji_animator模块，跳过动态效果生成")
            except Exception as e:
                print(f"创建动态效果时出错: {str(e)}")

        # 保存到数据库
        output_url = f"/uploads/{file_name}"
        
        if user_id:
            history = History(
                user_id=user_id,
                prompt_text=text,
                style=style,
                output_url=output_url,
                is_dynamic=is_dynamic
            )
            history.save()

        return {
            'status': 'success',
            'output_url': output_url
        }
        
    @staticmethod
    def batch_generate_emoji(prompts, style='cartoon', is_dynamic=False, user_id=None):
        """批量生成表情包"""
        if not prompts or len(prompts) == 0:
            return {'status': 'error', 'message': '生成文本不能为空'}, 400
            
        # 限制批量生成数量
        if len(prompts) > 5:
            return {'status': 'error', 'message': '批量生成最多支持5个表情包'}, 400
        
        results = []
        
        # 调用Stable Diffusion API
        headers = {
            "Authorization": f"Bearer {HF_API_KEY}"
        }
        
        # 根据风格调整提示词
        style_prompts = {
            'cartoon': 'cartoon style, cute, simple, ',
            'realistic': 'realistic style, detailed, ',
            'funny': 'funny, exaggerated, comic style, ',
            'cute': 'kawaii, adorable, chibi style, '
        }
        
        for text in prompts:
            prompt = f"{style_prompts.get(style, '')}emoji of {text}"
            
            try:
                response = requests.post(HF_API_URL, headers=headers, json={
                    "inputs": prompt,
                }, timeout=30)
                
                if response.status_code != 200:
                    continue
                
                # 保存图片
                image = Image.open(io.BytesIO(response.content))
                file_name = f"{uuid.uuid4()}.png"
                file_path = os.path.join(UPLOAD_FOLDER, file_name)
                image.save(file_path)
                
                # 如果是动态表情包，进行额外处理
                if is_dynamic:
                    try:
                        from utils.emoji_animator import EmojiAnimator
                        gif_file_name = f"{uuid.uuid4()}.gif"
                        gif_file_path = os.path.join(UPLOAD_FOLDER, gif_file_name)
                        
                        # 创建动画效果
                        animator = EmojiAnimator(file_path, gif_file_path)
                        effect_success = animator.create_bounce_effect()
                        
                        if effect_success:
                            # 使用GIF文件路径
                            file_name = gif_file_name
                            file_path = gif_file_path
                    except Exception as e:
                        print(f"创建动态效果时出错: {str(e)}")
                
                # 添加到结果列表
                output_url = f"/uploads/{file_name}"
                results.append({
                    'text': text,
                    'output_url': output_url
                })
                
                # 保存到数据库
                if user_id:
                    history = History(
                        user_id=user_id,
                        prompt_text=text,
                        style=style,
                        output_url=output_url,
                        is_dynamic=is_dynamic
                    )
                    history.save()
                    
            except Exception as e:
                print(f"处理提示词 '{text}' 时出错: {str(e)}")
                continue
        
        return {
            'status': 'success',
            'results': results
        }
    @staticmethod
    def advanced_generate_emoji(text, style='cartoon', is_dynamic=False, quality=75, 
                               style_strength=0.7, animation_type='bounce', user_id=None):
        """高级参数生成表情包"""
        if not text:
            return {'status': 'error', 'message': '文本内容不能为空'}, 400
            
        # 检查API密钥
        if not HF_API_KEY:
            return {'status': 'error', 'message': 'API密钥未配置，无法生成图片'}, 500
            
        # 调用Stable Diffusion API
        headers = {
            "Authorization": f"Bearer {HF_API_KEY}"
        }
        
        # 根据风格调整提示词
        style_prompts = {
            'cartoon': 'cartoon style, cute, simple, ',
            'realistic': 'realistic style, detailed, ',
            'funny': 'funny, exaggerated, comic style, ',
            'cute': 'kawaii, adorable, chibi style, ',
            'pixel': 'pixel art style, retro, 8-bit, ',
            'watercolor': 'watercolor painting style, artistic, soft, ',
            'sketch': 'pencil sketch style, hand-drawn, ',
            'anime': 'anime style, japanese, manga, '
        }
        
        # 根据风格强度调整提示词
        base_prompt = f"{style_prompts.get(style, '')}emoji of {text}"
        # 这里可以根据style_strength调整提示词权重，简化版本
        prompt = base_prompt
        
        try:
            response = requests.post(HF_API_URL, headers=headers, json={
                "inputs": prompt,
            }, timeout=30)
            
            if response.status_code != 200:
                return {
                    'status': 'error',
                    'message': f'图片生成失败，状态码: {response.status_code}'
                }, 500
        except requests.exceptions.RequestException as e:
            return {
                'status': 'error',
                'message': f'API请求失败: {str(e)}'
            }, 500
            
        # 保存图片
        try:
            image = Image.open(io.BytesIO(response.content))
            file_name = f"{uuid.uuid4()}.png"
            file_path = os.path.join(UPLOAD_FOLDER, file_name)
            image.save(file_path, quality=quality)
        except Exception as e:
            return {
                'status': 'error',
                'message': f'图片处理失败: {str(e)}'
            }, 500
            
        # 如果是动态表情包，进行额外处理
        if is_dynamic:
            try:
                from utils.emoji_animator import EmojiAnimator
                gif_file_name = f"{uuid.uuid4()}.gif"
                gif_file_path = os.path.join(UPLOAD_FOLDER, gif_file_name)
                
                # 创建动画效果
                animator = EmojiAnimator(file_path, gif_file_path)
                
                # 根据选择的动画类型应用不同效果
                effect_success = False
                if animation_type == 'bounce':
                    effect_success = animator.create_bounce_effect()
                elif animation_type == 'shake':
                    effect_success = animator.create_shake_effect()
                elif animation_type == 'rotate':
                    effect_success = animator.create_rotate_effect()
                
                if effect_success:
                    # 使用GIF文件路径
                    file_name = gif_file_name
                    file_path = gif_file_path
                else:
                    print("动态效果创建失败，使用原始图片")
            except ImportError:
                print("未找到emoji_animator模块，跳过动态效果生成")
            except Exception as e:
                print(f"创建动态效果时出错: {str(e)}")
                
        # 保存到数据库
        output_url = f"/uploads/{file_name}"
        
        if user_id:
            # 创建参数JSON
            params = {
                'quality': quality,
                'style_strength': style_strength,
                'animation_type': animation_type if is_dynamic else None
            }
            
            history = History(
                user_id=user_id,
                prompt_text=text,
                style=style,
                output_url=output_url,
                is_dynamic=is_dynamic,
                animation_type=animation_type if is_dynamic else None,
                params=params
            )
            history.save()
            @staticmethod
            def get_user_history(user_id, page=1, per_page=10):
                """获取用户的表情包生成历史"""
                try:
                    history = History.find_by_user_id(user_id)
                    
                    # 分页处理
                    start = (page - 1) * per_page
                    end = start + per_page
                    paginated_history = history[start:end]
                    
                    return {
                        'status': 'success',
                        'history': paginated_history,
                        'total': len(history),
                        'page': page,
                        'per_page': per_page
                    }
                except Exception as e:
                    return {
                        'status': 'error',
                        'message': f'获取历史记录失败: {str(e)}'
                    }, 500
                @staticmethod
                def delete_emoji(history_id, user_id):
                    """删除表情包及其历史记录"""
                    try:
                        history = History.find_by_id(history_id)
                        if not history:
                            return {
                                'status': 'error',
                                'message': '表情包不存在'
                            }, 404
                            
                        if history['user_id'] != user_id:
                            return {
                                'status': 'error',
                                'message': '无权删除此表情包'
                            }, 403
                            
                        # 删除文件
                        file_path = os.path.join(UPLOAD_FOLDER, history['output_url'].split('/')[-1])
                        if os.path.exists(file_path):
                            os.remove(file_path)
                            
                        # 删除数据库记录
                        History.delete(history_id)
                        
                        return {
                            'status': 'success',
                            'message': '删除成功'
                        }
                    except Exception as e:
                        return {
                            'status': 'error',
                            'message': f'删除失败: {str(e)}'
                        }, 500
                @staticmethod
                def update_emoji_info(history_id, user_id, data):
                    """更新表情包信息"""
                    try:
                        history = History.find_by_id(history_id)
                        if not history:
                            return {
                                'status': 'error',
                                'message': '表情包不存在'
                            }, 404
                            
                        if history['user_id'] != user_id:
                            return {
                                'status': 'error',
                                'message': '无权修改此表情包'
                            }, 403
                            
                        # 更新数据库记录
                        History.update(history_id, data)
                        
                        return {
                            'status': 'success',
                            'message': '更新成功'
                        }
                    except Exception as e:
                        return {
                            'status': 'error',
                            'message': f'更新失败: {str(e)}'
                        }, 500
                @staticmethod
                def search_emoji(keyword, page=1, per_page=10):
                    """搜索表情包"""
                    try:
                        history = History.search(keyword)
                        
                        # 分页处理
                        start = (page - 1) * per_page
                        end = start + per_page
                        paginated_results = history[start:end]
                        
                        return {
                            'status': 'success',
                            'results': paginated_results,
                            'total': len(history),
                            'page': page,
                            'per_page': per_page
                        }
                    except Exception as e:
                        return {
                            'status': 'error',
                            'message': f'搜索失败: {str(e)}'
                        }, 500
        return {
            'status': 'success',
            'output_url': output_url
        }